Skip to main content

Chapter 21 - Remote state with two projects

Referencing another state in another project

Overview​


This is when you have some resources managed by one Terraform state file and you want to reference those resources in a completely separate project.

Terraform Project 1:

  • RG, Vnet, Subnet, NICs, Public IP

Terraform Project 2:

  • Virtual Machine
# Terraform Remote State Datasource
data "terraform_remote_state" "project1" {
backend = "azurerm"
config = {
resource_group_name = "terraform-p1-storage-rg"
storage_account_name = "terraformstatep1"
container_name = "tfstatefiles"
key = "network-terraform.tfstate"
}
}

## VM resource block
# Resource: Azure Linux Virtual Machine
resource "azurerm_linux_virtual_machine" "mylinuxvm" {
name = local.vm_name
computer_name = local.vm_name # Hostname of the VM
size = "Standard_DS1_v2"
admin_username = "azureuser"
#resource_group_name = azurerm_resource_group.myrg.name
#location = azurerm_resource_group.myrg.location
# Getting Data using Terraform Remote State Datasource from Project-1
resource_group_name = data.terraform_remote_state.project1.outputs.resource_group_name
location = data.terraform_remote_state.project1.outputs.resource_group_location
# Getting the network interface IDs from the files in project 1
network_interface_ids = [data.terraform_remote_state.project1.outputs.network_interface_id]
admin_ssh_key {